import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/managemodel.dart';
import 'package:toast/toast.dart';

class MergeSubmitScreen extends StatelessWidget {
  Merge merge;

  MergeSubmitScreen({
    this.merge,
  });

  @override
  Widget build(BuildContext context) {
    return MergeSubmitScreenPage(merge: merge);
  }
}

class MergeSubmitScreenPage extends StatefulWidget {
  Merge merge;

  MergeSubmitScreenPage({
    this.merge,
  });

  @override
  _MergeSubmitScreenPageState createState() => _MergeSubmitScreenPageState(merge: merge);
}

class _MergeSubmitScreenPageState extends BaseState<MergeSubmitScreenPage> {
  Merge merge;

  _MergeSubmitScreenPageState({
    this.merge,
  });

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<ItemSkuListDTO> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Merge(LPN):Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    next = "Merge";
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 0, top: 0, right: 0, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 40),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 25,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        print(text); //拿到扫描结果
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "input container number",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 0, right: 0),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        data = merge.lpn1ItemVo.itemSkuList;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        Utils.getStringisEmpty(merge.lpn1ItemVo.lpn),
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        data = merge.lpn2ItemVo.itemSkuList;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        Utils.getStringisEmpty(merge.lpn2ItemVo.lpn),
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 0, right: 0, top: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        ItemSkuListDTO tally = data[index];
        return Column(
          children: [
            Text(
              "${Utils.getStringisEmpty(tally.sku)}(${Utils.getStringisInteger(tally.qty)})",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Please enter batch #", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if ((textEditingController.text!=merge.lpn1ItemVo.lpn) && (textEditingController.text!=merge.lpn2ItemVo.lpn)) {
      Toast.show("must be ${merge.lpn1ItemVo.lpn} or ${merge.lpn2ItemVo.lpn}", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    mergeSubmit();
  }

  void mergeSubmit() async {
    updateHint('');
    MergeQr mergeQr = new MergeQr();
    mergeQr.lpn1 = merge.lpn1ItemVo.lpn;
    mergeQr.lpn2 = merge.lpn2ItemVo.lpn;
    mergeQr.mergeLpn = textEditingController.text;

    String json = jsonEncode(mergeQr);

    // 显示加载中对话框
    LoadingIndicator.show(context, title: "Submit...");

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.merge, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
